package com.tuanzi.loan.business.service.settlementsystem.impl;

import com.tuanzi.loan.business.entity.settlementsystem.*;
import com.tuanzi.loan.business.repository.settlementsystem.SettlementBillAnnexRepository;
import com.tuanzi.loan.business.repository.settlementsystem.SettlementBillRepository;
import com.tuanzi.loan.business.repository.settlementsystem.SettlementIncomeRepository;
import com.tuanzi.loan.business.repository.settlementsystem.SettlementPrepayRepository;
import com.tuanzi.loan.business.service.settlementsystem.BillStatus;
import com.tuanzi.loan.business.service.settlementsystem.RemainType;
import com.tuanzi.loan.business.service.settlementsystem.SettlementBillService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.repository.JPAAuditRepository;
import com.tuanzi.loan.core.service.BaseAuditServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.settlementsystem.SettlementBillRequest;
import com.tuanzi.loan.vo.response.settlementsystem.SettlementBillResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author caiwanlin
 * @create 2018-08-24 16:25
 */
@Debug
@Service
@Transactional
@Retryable(value = {RetryException.class})
public class SettlementBillServiceImpl extends BaseAuditServiceImpl<SettlementBill,Long> implements SettlementBillService {
    @Autowired
    private SettlementBillRepository settlementBillRepository;

    @Autowired
    private SettlementIncomeRepository settlementIncomeRepository;

    @Autowired
    private SettlementPrepayRepository settlementPrepayRepository;

    @Autowired
    private SettlementBillAnnexRepository settlementBillAnnexRepository;

    @Override
    public Page<SettlementBillResponse> list(PageSearcher<SettlementBillRequest> pageSearcher) {
        return settlementBillRepository.list(pageSearcher.getSearchCondition(),pageSearcher.getPageable());
    }

    @Override
    public SettlementBill structureSettlementBill(SettlementCompany settlementCompany) {
        SettlementBill bill = new SettlementBill();
        bill.setCompanyId(settlementCompany.getId());
        bill.setCompanyName(settlementCompany.getCompanyName());
        bill.setBillContent(settlementCompany.getBillContent());
        bill.setTaxNumber(settlementCompany.getTaxNumber());
        bill.setPhone(settlementCompany.getPhone());
        bill.setBillType(settlementCompany.getBillType());
        bill.setBankAccount(settlementCompany.getBankAccount());
        bill.setBankAddress(settlementCompany.getBankAddress());
        bill.setBankNumber(settlementCompany.getBankNumber());
        bill.setBillAddress(settlementCompany.getBillAddress());
        bill.setReceiveName(settlementCompany.getReceiveName());
        bill.setReceivePhone(settlementCompany.getReceivePhone());
        bill.setReceiveAddress(settlementCompany.getReceiveAddress());
        return bill;
    }

    @Override
    public void onSave(SettlementBill settlementBill, List<Long> selectIncomeId,List<SettlementBillAnnex> billAnnexeList) {
        //保存开票记录
        settlementBill.setBillStatus(BillStatus.COMMISSIONER_CHECK_BILL.index);//财务专员审核
        saveOrUpdate(settlementBill);


        if (settlementBill.getRecordType() == RemainType.EXPEND.index){//消耗记录更改开票状态和关联开票id
            selectIncomeId.forEach(id ->{
                SettlementIncome one = settlementIncomeRepository.findOne(id);
                one.setBillStatus(BillStatus.COMMISSIONER_CHECK_BILL.index);
                one.setBillId(settlementBill.getId());
                settlementIncomeRepository.save(one);
            });
        }
        else if (settlementBill.getRecordType() == RemainType.PREPAY.index){
            selectIncomeId.forEach(id->{//预付记录更改开票状态和关联开票id
                SettlementPrepay one = settlementPrepayRepository.findOne(id);
                one.setBillStatus(BillStatus.COMMISSIONER_CHECK_BILL.index);
                one.setBillId(settlementBill.getId());
                settlementPrepayRepository.save(one);
            });
        }

        //保存附件
        if (billAnnexeList != null && !billAnnexeList.isEmpty()){
            billAnnexeList.forEach(e->e.setBillId(settlementBill.getId()));
            settlementBillAnnexRepository.save(billAnnexeList);
        }



    }

    @Override
    public String validateBill(SettlementBill settlementBill) {
        String result = null;

        if (StringUtils.isBlank(settlementBill.getCompanyName())){
            result="开票主体名称为空";
            return result;
        }
        if (settlementBill.getBillContent() == null){
            result="请选择开票内容";
            return result;
        }
        if (settlementBill.getReceiveCompany() == null){
            result="请选择开票公司";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getTaxNumber())){
            result = "开票登记税号为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getPhone())){
            result = "电话号码为空";
            return result;
        }
        if (settlementBill.getBillType() == null){
            result = "请选择发票类型";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBankAccount())){
            result = "开票开户账户为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBankAddress())){
            result = "开票开户支行为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBankNumber())){
            result = "开票主体名称为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBankNumber())){
            result = "开票开户卡号为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getBillAddress())){
            result = "开票地址为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getReceiveName())){
            result = "开票收件人姓名为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getReceivePhone())){
            result = "开票收件人手机为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getReceiveAddress())){
            result = "开票收件地址为空";
            return result;
        }
        if (StringUtils.isBlank(settlementBill.getCheckAccount())){
            result = "开票财务审核人为空";
            return result;
        }
        if (settlementBill.getBillAmount() == null){
            result = "开票总结算金额为空";
            return result;
        }
        return null;
    }

    /**
     * 改变开票记录状态
     * @param businessKey
     * @param taskVariables
     */
    @Override
    public void changeBillStatus(String businessKey, Map<String, Object> taskVariables) {
        if (StringUtils.isBlank(businessKey)){
            return;
        }
        long billId = Long.parseLong(businessKey.split(":")[1]);
        SettlementBill bill = settlementBillRepository.findOne(billId);
        String condition = null;
        Object outcome = taskVariables.get("outcome");
        if (outcome == null){
           return;
        }
        condition = (String) outcome;
        if ("usertask2".equals(condition)){//财务专员审核通过
            bill.setBillStatus(BillStatus.MANAGER_CHECK_BILL.index);
            settlementBillRepository.save(bill);
            if (bill.getRecordType() == RemainType.EXPEND.index){
                settlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(BillStatus.MANAGER_CHECK_BILL.index);
                    settlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == RemainType.PREPAY.index){
                settlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(BillStatus.MANAGER_CHECK_BILL.index);
                    settlementPrepayRepository.save(prepay);
                });
            }
        }
        else if ("usertask3".equals(condition)){//财务经理审核通过
            bill.setBillStatus(BillStatus.BILL_NUM_WRITE.index);
            settlementBillRepository.save(bill);
            if (bill.getRecordType() == RemainType.EXPEND.index){
                settlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(BillStatus.BILL_NUM_WRITE.index);
                    settlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == RemainType.PREPAY.index){
                settlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(BillStatus.BILL_NUM_WRITE.index);
                    settlementPrepayRepository.save(prepay);
                });
            }
        }
        else if ("cancelendevent".equals(condition)){//作废
            bill.setBillStatus(BillStatus.CANCEL.index);
            settlementBillRepository.save(bill);
            if (bill.getRecordType() == RemainType.EXPEND.index){
                settlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(BillStatus.NO_BILL.index);
                    income.setBillId(null);
                    settlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == RemainType.PREPAY.index){
                settlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(BillStatus.NO_BILL.index);
                    prepay.setBillId(null);
                    settlementPrepayRepository.save(prepay);
                });
            }
        }
        else if ("passendevent".equals(condition)){//审核通过
            bill.setBillStatus(BillStatus.HAD_BILL.index);
            settlementBillRepository.save(bill);
            if (bill.getRecordType() == RemainType.EXPEND.index){
                settlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(BillStatus.HAD_BILL.index);
                    settlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == RemainType.PREPAY.index){
                settlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(BillStatus.HAD_BILL.index);
                    settlementPrepayRepository.save(prepay);
                });
            }
        }
    }

    @Override
    public void changeCancelBillStatus(String businessKey, Map<String, Object> taskVariables) {
        if (StringUtils.isBlank(businessKey)){
            return;
        }
        long billId = Long.parseLong(businessKey.split(":")[1]);
        SettlementBill bill = settlementBillRepository.findOne(billId);
        String condition = null;
        Object outcome = taskVariables.get("outcome");
        if (outcome == null){
            return;
        }
        condition = (String) outcome;
        if ("cancelendevent".equals(condition)){//作废拒绝
            bill.setBillStatus(BillStatus.HAD_BILL.index);
            settlementBillRepository.save(bill);
            if (bill.getRecordType() == RemainType.EXPEND.index){
                settlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(BillStatus.HAD_BILL.index);
                    settlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == RemainType.PREPAY.index){
                settlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(BillStatus.HAD_BILL.index);
                    settlementPrepayRepository.save(prepay);
                });
            }
        }
        else if ("passendevent".equals(condition)){//审核通过
            bill.setBillStatus(BillStatus.OBSOLETE.index);
            settlementBillRepository.save(bill);
            if (bill.getRecordType() == RemainType.EXPEND.index){
                settlementIncomeRepository.findAllByBillId(billId).forEach(income->{
                    income.setBillStatus(BillStatus.NO_BILL.index);
                    income.setBillId(null);
                    settlementIncomeRepository.save(income);
                });
            }
            else if (bill.getRecordType() == RemainType.PREPAY.index){
                settlementPrepayRepository.findAllByBillId(billId).forEach(prepay->{
                    prepay.setBillStatus(BillStatus.NO_BILL.index);
                    prepay.setBillId(null);
                    settlementPrepayRepository.save(prepay);
                });
            }
        }
    }


    @Override
    protected JPAAuditRepository<SettlementBill, Long> getRepository() {
        return settlementBillRepository;
    }
}
